#!/usr/bin/env bash
# Copyright 2023 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -euo pipefail
IFS=$'\n\t'

cd "$(dirname "$0")"

if ((BASH_VERSINFO[0] < 4)); then
    echo "At least bash version 4 is required to run this script"
    exit 1
fi

# Change the following configurations to adapt the resulting ignitions files.
declare -A CONFIGURATIONS=(
    ["crio_cgroupv1"]="root cgroupv1 criu-enabled"
    ["crio_cgroupv1_eventedpleg"]="root cgroupv1 eventedpleg"
    ["crio_cgroupv1_hugepages"]="root cgroupv1 hugepages"
    ["crio_cgroupv2"]="root"
    ["crio_cgroupv2_drop_infra_ctr"]="drop-infra-ctr"
    ["crio_cgroupv2_swap1g"]="root swap-1G"
    ["crio_cgroupv2_imagefs"]="root imagefs"
    ["crio_cgroupv2_splitfs"]="root splitfs"
    ["crio_cgroupv2_hugepages"]="root hugepages"
    ["crio_cgroupv2_userns"]="root userns crun-enabled"
)

CONTAINER_RUNTIME=$(which podman 2>/dev/null) ||
    CONTAINER_RUNTIME=$(which nerdctl 2>/dev/null) ||
    CONTAINER_RUNTIME=$(which docker 2>/dev/null)

if [[ -z "$CONTAINER_RUNTIME" ]]; then
    echo "Neither podman, nerdctl nor docker found in \$PATH"
    exit 1
fi

YQ_IMAGE=mikefarah/yq:4
BUTANE_IMAGE=quay.io/coreos/butane:release
BASE_PATH=base

# Pull the latest image version
for IMAGE in $YQ_IMAGE $BUTANE_IMAGE; do
    $CONTAINER_RUNTIME pull "$IMAGE"
done

merge() {
    ARGS=()
    for ARG in "${@:2}"; do
        ARGS+=("$BASE_PATH/$ARG.yaml")
    done

    set -x
    # shellcheck disable=SC2016
    $CONTAINER_RUNTIME run --privileged -i --rm -v "$PWD":/w -w /w $YQ_IMAGE \
        ea '. as $item ireduce ({}; . *+ $item)' "${ARGS[@]}" >"$1.yaml"
    { set +x; } 2>/dev/null
}

for i in "${!CONFIGURATIONS[@]}"; do
    echo "Building ${i}"

    IFS=' ' read -r -a ARGS <<<"${CONFIGURATIONS[$i]}"
    merge "$i" "${ARGS[@]}"

    set -x
    $CONTAINER_RUNTIME run --privileged -i --rm -v "$PWD":/w -w /w $BUTANE_IMAGE \
        -ps -d $BASE_PATH <"$i.yaml" >../"$i.ign"
    { set +x; } 2>/dev/null
done
